#include "missileactor.h"

MissileActor::MissileActor(f32 xi, f32 yi, f32 xf, f32 yf, Type owner, int splitafter)
  : state(MS_NULL), xi(xi), yi(yi), xf(xf), yf(yf), x(xi), y(yi),
    d(0), t(0), owner(owner), splitTime(splitafter)
{
  maxd = sqrt((xf-xi)*(xf-xi)+(yf-yi)*(yf-yi));
  theta = atan2(xi-xf,yf-yi);
  splitParent = NULL;
}

extern const f32 SILOY;

void MissileActor::explode()
{
  if(state != MS_FLIGHT)
    return;
  state = MS_EXPLODE;
  if(splitParent)
    splitParent->notifyExploded();
}

void MissileActor::notifyExploded()
{
  splitCount--;
  if(splitCount <= 0)
    state = MS_FINISHED;
}


void MissileActor::split(int n)
{
  splitCount = n;
  state = MS_DIDSPLIT;
}

void MissileActor::activate()
{
  x = xi;
  y = yi;
  d = 0;
  t = 0;
  maxd = sqrt((xf-xi)*(xf-xi)+(yf-yi)*(yf-yi));
  theta = atan2(xf-xi,yi-yf);
  state = MS_FLIGHT;
}

void MissileActor::update()
{
  switch(state) {
    case MS_FLIGHT:
      if(owner == PLAYER)
        d += MSPEED;
      else if(owner == ENEMY)
        d += ENEMYSPEED;
      if(d >= maxd) {
        x = xf;
        y = yf;
        explode();
      } else {
        x = xi + d * sin(theta);
        y = yi - d * cos(theta);
      }
      if(splitTime != -1 && t >= splitTime)
        state = MS_SPLITME;
      break;
    case MS_SPLITME:
      state = MS_DIDSPLIT;
      break;
    case MS_DIDSPLIT:
      if(splitCount <= 0)
        state = MS_FINISHED;
      break;
    case MS_EXPLODE:
      // Shouldn't get here, but just in case
      state = MS_FINISHED;
      break;
    default:
      break;
  }

  if(state != MS_NULL)
    t++;
}
